﻿using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Common.APP;
using DiLe.Mes.Model.Common.WorkOrder.Entity;
using DiLe.Mes.Model.Common.WorkOrder.Relation;
using DiLe.Mes.Model.Local.Entity;
using EasyNetQ;
using MapleLeaf.Core.AppSetting;
using MapleLeaf.Core.EventBus;
using Quartz;

namespace DiLe.Mes.Local.Jobs {
    /// <summary>
    /// 
    /// </summary>
    [DisallowConcurrentExecution]
    public class DataPushJob : IJob {
        private readonly static IBus _ibus;
        static DataPushJob() {
            _ibus = AppHelper.GetService<IBus>();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context) {
            //using var rabbitMQ = new EventBusRabbitMQ(rabbitconn);


            //var where = Expressionable.Create<EquipmentStatusInfoEntity>();
            //var startDate = DateTime.Now.AddMinutes(-5);
            //var endDate = DateTime.Now;
            //where.And(p => p.CreateTime >= startDate);
            //where.And(p => p.CreateTime <= endDate);
            //var eqStatuslist = await SqlSugarHelper.MasterDb.Queryable<EquipmentStatusInfoEntity>().Where(where.ToExpression()).ToListAsync();

            await PushPointInfoAsync();
            await PushOtherPointInfoAsync();
            await PushAOIPointInfoAsync();
            await PushPMPointInfoAsync();
            await PushEMPointInfoAsync();
            await PushTrimPointInfoAsync();


            await PushReportWorkRecordAsync();
            await PushStartWorkRecord2MouldInfoAsync();
            await PushStartWorkRecordAsync();
        }

        #region 
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static async Task PushPointInfoAsync() {
            var where = Expressionable.Create<PointInfoEntity>();
            var startDate = DateTime.Now.Hour < 1 ? DateTime.Now.Date : DateTime.Now.AddHours(-1);
            where.And(p => p.CreateTime >= startDate);
            var list = await SqlSugarHelper.LocalDb.Queryable<PointInfoEntity>().Where(where.ToExpression()).ToListAsync();
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderByDescending(p => p.CreateTime).FirstOrDefault()));
            var pushDatas = new List<PointInfoEntity>();
            foreach (var item in dataMap) {
                var data = item.Item2;
                if (data == null || data.IsPushed == true) {
                    continue;
                }

                pushDatas.Add(data);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "PointInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            pushDatas.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.LocalDb.Updateable(pushDatas).ExecuteCommandAsync();
            var delDate = DateTime.Now.Date.AddDays(-15);
            _ = await SqlSugarHelper.LocalDb.Deleteable<PointInfoEntity>().Where(x => x.CreateTime <= delDate).ExecuteCommandAsync();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static async Task PushOtherPointInfoAsync() {
            var where = Expressionable.Create<OtherPointInfoEntity>();
            var startDate = DateTime.Now.Hour < 1 ? DateTime.Now.Date : DateTime.Now.AddHours(-1);
            where.And(p => p.CreateTime >= startDate);
            var list = await SqlSugarHelper.LocalDb.Queryable<OtherPointInfoEntity>().Where(where.ToExpression()).ToListAsync();
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderByDescending(p => p.CreateTime).FirstOrDefault()));
            var pushDatas = new List<OtherPointInfoEntity>();
            foreach (var item in dataMap) {
                var data = item.Item2;
                if (data == null || data.IsPushed == true) {
                    continue;
                }
                pushDatas.Add(data);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "OtherPointInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            pushDatas.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.LocalDb.Updateable(pushDatas).ExecuteCommandAsync();
            var delDate = DateTime.Now.Date.AddDays(-15);
            _ = await SqlSugarHelper.LocalDb.Deleteable<OtherPointInfoEntity>().Where(x => x.CreateTime <= delDate).ExecuteCommandAsync();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static async Task PushAOIPointInfoAsync() {
            var where = Expressionable.Create<AOIPointInfoEntity>();
            var startDate = DateTime.Now.Hour < 1 ? DateTime.Now.Date : DateTime.Now.AddHours(-1);
            where.And(p => p.CreateTime >= startDate);
            var list = await SqlSugarHelper.LocalDb.Queryable<AOIPointInfoEntity>().Where(where.ToExpression()).OrderByDescending(p => p.CreateTime).ToListAsync();
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderByDescending(p => p.CreateTime).FirstOrDefault()));
            var pushDatas = new List<AOIPointInfoEntity>();
            foreach (var item in dataMap) {
                var data = item.Item2;
                if (data == null || data.IsPushed == true) {
                    continue;
                }
                //var status = statusInfos?.FirstOrDefault(x => x.DeviceNo == item.Key);
                //data.EquipmentStatus = status == null ? "在线" : "离线";
                pushDatas.Add(data);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "AOIPointInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            pushDatas.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.LocalDb.Updateable(pushDatas).ExecuteCommandAsync();
            var delDate = DateTime.Now.Date.AddDays(-15);
            _ = await SqlSugarHelper.LocalDb.Deleteable<AOIPointInfoEntity>().Where(x => x.CreateTime <= delDate).ExecuteCommandAsync();

        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static async Task PushPMPointInfoAsync() {
            var where = Expressionable.Create<FMPointInfoEntity>();
            var startDate = DateTime.Now.Hour < 1 ? DateTime.Now.Date : DateTime.Now.AddHours(-1);
            where.And(p => p.CreateTime >= startDate);
            var list = await SqlSugarHelper.LocalDb.Queryable<FMPointInfoEntity>().Where(where.ToExpression()).ToListAsync();
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderByDescending(p => p.CreateTime).FirstOrDefault()));
            var pushDatas = new List<FMPointInfoEntity>();
            foreach (var item in dataMap) {
                var data = item.Item2;
                if (data == null || data.IsPushed == true) {
                    continue;
                }
                pushDatas.Add(data);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "PMPointInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            pushDatas.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.LocalDb.Updateable(pushDatas).ExecuteCommandAsync();
            var delDate = DateTime.Now.Date.AddDays(-15);
            _ = await SqlSugarHelper.LocalDb.Deleteable<FMPointInfoEntity>().Where(x => x.CreateTime <= delDate).ExecuteCommandAsync();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static async Task PushEMPointInfoAsync() {
            var where = Expressionable.Create<EMPointInfoEntity>();
            var startDate = DateTime.Now.Hour < 1 ? DateTime.Now.Date : DateTime.Now.AddHours(-1);
            where.And(p => p.CreateTime >= startDate);
            var list = await SqlSugarHelper.LocalDb.Queryable<EMPointInfoEntity>().Where(where.ToExpression()).ToListAsync();
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderByDescending(p => p.CreateTime).FirstOrDefault()));
            var pushDatas = new List<EMPointInfoEntity>();
            foreach (var item in dataMap) {
                var data = item.Item2;
                if (data == null || data.IsPushed == true) {
                    continue;
                }
                pushDatas.Add(data);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "EMPointInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            pushDatas.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.LocalDb.Updateable(pushDatas).ExecuteCommandAsync();
            var delDate = DateTime.Now.Date.AddDays(-15);
            _ = await SqlSugarHelper.LocalDb.Deleteable<EMPointInfoEntity>().Where(x => x.CreateTime <= delDate).ExecuteCommandAsync();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static async Task PushTrimPointInfoAsync() {
            var where = Expressionable.Create<TrimPointInfoEntity>();
            var startDate = DateTime.Now.Hour < 1 ? DateTime.Now.Date : DateTime.Now.AddHours(-1);
            where.And(p => p.CreateTime >= startDate);
            var list = await SqlSugarHelper.LocalDb.Queryable<TrimPointInfoEntity>().Where(where.ToExpression()).OrderByDescending(p => p.CreateTime).ToListAsync();
            var dataMap = list.GroupBy(x => x.DeviceNo).Select(x => (x.Key, x.OrderByDescending(p => p.CreateTime).FirstOrDefault()));
            var pushDatas = new List<TrimPointInfoEntity>();
            foreach (var item in dataMap) {
                var data = item.Item2;
                if (data == null || data.IsPushed == true) {
                    continue;
                }
                //var status = statusInfos?.FirstOrDefault(x => x.DeviceNo == item.Key);
                //data.EquipmentStatus = status == null ? "在线" : "离线";
                pushDatas.Add(data);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "TrimlPointInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            pushDatas.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.LocalDb.Updateable(pushDatas).ExecuteCommandAsync();
            var delDate = DateTime.Now.Date.AddDays(-15);
            _ = await SqlSugarHelper.LocalDb.Deleteable<TrimPointInfoEntity>().Where(x => x.CreateTime <= delDate).ExecuteCommandAsync();

        }
        #endregion
        #region  开工报工数据
        /// <summary>
        /// 推送开工数据
        /// </summary>
        /// <returns></returns>
        private static async Task PushStartWorkRecordAsync() {
            var where = Expressionable.Create<StartWorkRecordEntity>();
            var startDate = DateTime.Now.Date;
            where.And(p => p.CreateTime >= startDate);
            where.And(p => p.IsPushed == false || p.IsPushed == null);
            var list = await SqlSugarHelper.MasterDb.Queryable<StartWorkRecordEntity>().Where(where.ToExpression()).OrderByDescending(p => p.CreateTime).ToListAsync();
            if (list.None()) {
                return;
            }
            var model = new MessageModel() {
                SendMsg = list.ToJosn(),
                MsgSign = "StartWorkRecord"
            };
            _ibus.SendReceive.Send("data_push", model);
            list.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.MasterDb.Updateable(list).ExecuteCommandAsync();
        }
        /// <summary>
        /// 推送开工和模具
        /// </summary>
        /// <returns></returns>
        private async Task PushStartWorkRecord2MouldInfoAsync() {
            var where = Expressionable.Create<StartWorkRecord2MouldInfoEntity>();
            var startDate = DateTime.Now.Date;
            where.And(p => p.CreateTime >= startDate);
            where.And(p => p.IsPushed == false || p.IsPushed == null);
            var list = await SqlSugarHelper.MasterDb.Queryable<StartWorkRecord2MouldInfoEntity>().Where(where.ToExpression()).OrderByDescending(p => p.CreateTime).ToListAsync();
            if (list.None()) {
                return;
            }
            var model = new MessageModel() {
                SendMsg = list.ToJosn(),
                MsgSign = "StartWorkRecord2MouldInfo"
            };
            _ibus.SendReceive.Send("data_push", model);
            list.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.MasterDb.Updateable(list).ExecuteCommandAsync();
        }
        /// <summary>
        /// 推送报工数据
        /// </summary>
        /// <returns></returns>
        private static async Task PushReportWorkRecordAsync() {
            var where = Expressionable.Create<ReportWorkRecordEntity>();
            var startDate = DateTime.Now.Date;
            where.And(p => p.CreateTime >= startDate);
            where.And(p => p.IsPushed == false || p.IsPushed == null);
            var list = await SqlSugarHelper.MasterDb.Queryable<ReportWorkRecordEntity>().Where(where.ToExpression()).OrderByDescending(p => p.CreateTime).ToListAsync();
            if (list.None()) {
                return;
            }
            var model = new MessageModel() {
                SendMsg = list.ToJosn(),
                MsgSign = "ReportWorkRecord"
            };
            _ibus.SendReceive.Send("data_push", model);
            list.ForEach(p => p.IsPushed = true);
            _ = await SqlSugarHelper.MasterDb.Updateable(list).ExecuteCommandAsync();
        }
        #endregion  
    }
}
